package com.ss.mq.pattern.topic;

import com.rabbitmq.client.*;
import com.ss.mq.util.RabbitUtils;

import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @author 叁昇
 * @create 2020-12-19-15:48
 */
public class TopicConsumer {
    public static void main(String[] args) throws Exception {
        Connection connection = RabbitUtils.getConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare("topic_log", BuiltinExchangeType.TOPIC);

        // 自动生成队列名
        String queue = channel.queueDeclare().getQueue();

        System.out.print("请输入绑定键, 多个用空格隔开: ");
        String[] bindingString = new Scanner(System.in).nextLine().split("\\s");

        for (String bindingKey: bindingString) {
            channel.queueBind(queue, "topic_log", bindingKey);
        }

        System.out.println("等待接受数据...");

        DeliverCallback deliver = (s, delivery) -> {
            String msg = new String(delivery.getBody(), StandardCharsets.UTF_8);
            String routingKey = delivery.getEnvelope().getRoutingKey();
            System.out.println("收到: [ " + routingKey + " - " + msg + " ]");
        };

        CancelCallback cancel = s -> {};

        channel.basicConsume(queue, true, deliver, cancel);
    }
}
